<template>
  <a-modal
    title="修改头像"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :width="900"
    :footer="null"
    @cancel="cancelHandel"
  >
    <a-row :gutter="10">
      <a-col :span="17">
        <vue-cropper
          ref="cropper"
          class="cropper"
          :img="options.img"
          :output-size="options.size"
          :output-type="options.outputType"
          :info="true"
          :full="options.full"
          :can-move="options.canMove"
          :can-move-box="options.canMoveBox"
          :can-scale="true"
          :fixed-box="options.fixedBox"
          :original="options.original"
          :auto-crop="options.autoCrop"
          :auto-crop-width="options.autoCropWidth"
          :auto-crop-height="options.autoCropHeight"
          :center-box="options.centerBox"
          :high="options.high"
          :info-true="options.infoTrue"
          :max-img-size="options.maxImgSize"
          :limit-min-size="options.limitMinSize"
          @realTime="realTime"
        >
        </vue-cropper>
      </a-col>
      <a-col :span="7">
        <div class="cropper-cut">
          <a-image :src="previews" />
        </div>
        <div class="cropper-cut-two">
          <div>
            <a-image :src="previews" />
          </div>
          <div>
            <a-image :src="previews" />
          </div>
        </div>
      </a-col>
    </a-row>
    <div style="text-align: center; padding-top: 10px">
      <a-space>
        <a-upload
          name="file"
          :beforeUpload="beforeUpload"
          accept="image/png, image/jpeg, image/gif, image/jpg"
          :showUploadList="false"
        >
          <a-button>
            <template #icon>
              <cloud-upload-outlined />
            </template>
            选择图片
          </a-button>
        </a-upload>
        <a-button @click="changeScale(1)">放大</a-button>
        <a-button @click="changeScale(-1)">缩小</a-button>
        <a-button @click="cropper.refresh()">重置</a-button>
        <a-button @click="rotateLeft">向左旋转</a-button>
        <a-button @click="cropper.rotateRight()">向右旋转</a-button>
        <a-button type="primary" @click="finish('blob')">保存</a-button>
      </a-space>
    </div>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { message } from "ant-design-vue";
import { VueCropper } from "vue-cropper";
import { requestPost } from "@/api/service";

interface prevType {
  div: {
    width: string;
    height: string;
  };
  img: {
    width: string;
    height: string;
    transform: string;
  };
  url: string;
  h?: number;
  w?: number;
  html?: string;
}

export default defineComponent({
  name: "AvatarModal",
  components: {
    VueCropper,
  },
  setup(props, { emit }) {
    const cropper = ref(<any | null>null);
    const visible = ref(false);
    const id: any = ref(null);
    const confirmLoading = ref(false);
    const fileList = ref([]);
    const uploading = ref(false);
    const options = reactive(<any>{
      img: "",
      url: "",
      size: 1,
      full: false,
      outputType: "png",
      canMove: true,
      fixedBox: true, // 固定截图框大小 不允许改变
      fixed: true, // 是否开启截图框宽高固定比例
      fixedNumber: [3, 4], // 截图框的宽高比例  需要配合centerBox一起使用才能生效
      original: false,
      canMoveBox: true,
      autoCrop: true,
      autoCropWidth: 200,
      autoCropHeight: 200,
      centerBox: true,
      high: false,
      cropData: {},
      enlarge: 1,
      mode: "100px",
      maxImgSize: 3000,
      limitMinSize: 10,
    });
    const previews = ref(<prevType>{});

    const edit = (val) => {
      visible.value = true;
      id.value = val;
      /* 获取原始头像 */
    };
    const close = () => {
      id.value = null;
      visible.value = false;
    };
    const cancelHandel = () => {
      close();
    };
    const changeScale = (num) => {
      num = num || 1;
      cropper.value.changeScale(num);
    };
    const rotateLeft = () => {
      cropper.value.rotateLeft();
    };
    const rotateRight = () => {
      cropper.value.rotateRight();
    };
    const beforeUpload = (file) => {
      const reader = new FileReader();
      // 把Array Buffer转化为blob 如果是base64不需要
      // 转化为base64
      reader.readAsDataURL(file);
      reader.onload = () => {
        options.img = reader.result;
        // console.log(reader.result)
      };
      // 转化为blob
      // reader.readAsArrayBuffer(file)
      return false;
    };

    // 上传图片（点击上传按钮）
    const finish = (type) => {
      console.log("finish");
      const formData = new FormData();
      // 输出
      if (type === "blob") {
        cropper.value.getCropBlob((data) => {
          const img = window.URL.createObjectURL(data);
          cropper.value.model = true;
          cropper.value.modelSrc = img;
          formData.append("file", data, cropper.value.fileName);
          requestPost("/api/cropperpost", formData, {
            contentType: false,
            processData: false,
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }).then((response) => {
            console.log("upload response:", response);
            // let res = response.data
            // if (response.status === 'done') {
            //   imgFile = ''
            //   headImg = res.realPathList[0] // 完整路径
            //   uploadImgRelaPath = res.relaPathList[0] // 非完整路径
            //   message.success('上传成功')
            //   visible.value = false
            // }
            message.success("上传成功");
            // @ts-ignore
            emit("ok", response.data.url);
            visible.value = false;
          });
        });
      } else {
        cropper.value.getCropData((data) => {
          cropper.value.model = true;
          cropper.value.modelSrc = data;
        });
      }
    };
    const okHandel = () => {
      confirmLoading.value = true;
      setTimeout(() => {
        confirmLoading.value = false;
        close();
        message.success("上传头像成功");
      }, 2000);
    };

    const realTime = () => {
      cropper.value.getCropData((data) => {
        previews.value = data;
      });
    };

    return {
      cropper,
      visible,
      id,
      confirmLoading,
      fileList,
      uploading,
      options,
      previews,
      edit,
      close,
      cancelHandel,
      changeScale,
      rotateLeft,
      rotateRight,
      beforeUpload,
      finish,
      okHandel,
      realTime,
    };
  },
  methods: {},
});
</script>

<style lang="less" scoped>
.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 180px;
  height: 180px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
  }
}
.circle {
  border-radius: 50%;
}
.cropper {
  width: 600px;
  height: 420px;
}

.cropper-cut {
  width: 165px;
  height: 165px;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
}
.cropper-cut-two {
  padding-top: 10px;
  display: flex;
}
.cropper-cut-two > div:first-child {
  height: 100px;
  width: 100px;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
}
.cropper-cut-two > div:nth-child(2) {
  height: 60px;
  width: 60px;
  border: 1px solid #e9e9e9;
  margin-left: 5px;
  border-radius: 2px;
}
</style>
